﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace isky.Plugin
{
    public class SalesOrderYGCBSql
    {
        /// <summary>
        ///更加订单汇总报价利润
        /// </summary>
        /// <param name="service"></param>
        /// <param name="orderId"></param>
        /// <param name="ygcbId"></param>
        /// <param name="pre"></param>
        /// <returns></returns>
        public decimal GetYGCBInfo(IOrganizationService service, Guid orderId, Guid ygcbId, string pre)
        {

            //var fetchXml = "<fetch distinct='false' mapping='logical' aggregate='true' >" +
            //        "  <entity name='lux_quotemoldplasticscrap' >" +
            //        "    <attribute name='lux_totalpricebase' alias='totalpricebase' aggregate='sum' />" +
            //        "    <filter>" +
            //        "      <filter type='and' >" +
            //        "        <condition attribute='statecode' operator='eq' value='0' />" +
            //        "        <condition attribute='statuscode' operator='eq' value='1' />" +
            //        "        <condition attribute='lux_quotemoldplasticid' operator='eq' value='" + entityId + "' />" +
            //        "      </filter>" +
            //        "    </filter>" +
            //        "  </entity>" +
            //        "</fetch>";


            string parm = "";
            if (pre == "Delete")
            {
                parm = "<condition attribute='new_ygcbid' operator='ne' value='" + ygcbId + "' />";
            }
            string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' aggregate='true'>" +
                             " <entity name='new_ygcb'>" +
                             "   <attribute name='new_usdcost'  alias='usdcost' aggregate='sum'/>" +
                             "   <filter type='and'>" +
                            "      <condition attribute='new_case' operator='eq' value='" + orderId + "' />" + parm +
                             "   </filter>" +
                             " </entity>" +
                            "</fetch>";
            EntityCollection ygcbCollection = service.RetrieveMultiple(new FetchExpression(fetchXml));
            if (ygcbCollection != null && ygcbCollection.Entities.Count > 0)
            {
                if (ygcbCollection.Entities[0].GetAttributeDefaultValue<AliasedValue>("usdcost").Value != null)
                {
                    double usdcostus = (double)ygcbCollection.Entities[0].GetAttributeDefaultValue<AliasedValue>("usdcost").Value;
                    return Convert.ToDecimal(usdcostus);
                }
            }
            return 0;
        }
        /// <summary>
        /// 金额转换成中文大写金额
        /// </summary>
        /// <param name="LowerMoney">eg:10.74</param>
        /// <returns></returns>
        public string MoneyToUpper(string LowerMoney)
        {
            string functionReturnValue = null;
            bool IsNegative = false; // 是否是负数
            if (LowerMoney.Trim().Substring(0, 1) == "-")
            {
                // 是负数则先转为正数
                LowerMoney = LowerMoney.Trim().Remove(0, 1);
                IsNegative = true;
            }
            string strLower = null;
            string strUpart = null;
            string strUpper = null;
            int iTemp = 0;
            // 保留两位小数 123.489→123.49　　123.4→123.4
            LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString();
            if (LowerMoney.IndexOf(".") > 0)
            {
                if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2)
                {
                    LowerMoney = LowerMoney + "0";
                }
            }
            else
            {
                LowerMoney = LowerMoney + ".00";
            }
            strLower = LowerMoney;
            iTemp = 1;
            strUpper = "";
            while (iTemp <= strLower.Length)
            {
                switch (strLower.Substring(strLower.Length - iTemp, 1))
                {
                    case ".":
                        strUpart = "圆";
                        break;
                    case "0":
                        strUpart = "零";
                        break;
                    case "1":
                        strUpart = "壹";
                        break;
                    case "2":
                        strUpart = "贰";
                        break;
                    case "3":
                        strUpart = "叁";
                        break;
                    case "4":
                        strUpart = "肆";
                        break;
                    case "5":
                        strUpart = "伍";
                        break;
                    case "6":
                        strUpart = "陆";
                        break;
                    case "7":
                        strUpart = "柒";
                        break;
                    case "8":
                        strUpart = "捌";
                        break;
                    case "9":
                        strUpart = "玖";
                        break;
                }

                switch (iTemp)
                {
                    case 1:
                        strUpart = strUpart + "分";
                        break;
                    case 2:
                        strUpart = strUpart + "角";
                        break;
                    case 3:
                        strUpart = strUpart + "";
                        break;
                    case 4:
                        strUpart = strUpart + "";
                        break;
                    case 5:
                        strUpart = strUpart + "拾";
                        break;
                    case 6:
                        strUpart = strUpart + "佰";
                        break;
                    case 7:
                        strUpart = strUpart + "仟";
                        break;
                    case 8:
                        strUpart = strUpart + "万";
                        break;
                    case 9:
                        strUpart = strUpart + "拾";
                        break;
                    case 10:
                        strUpart = strUpart + "佰";
                        break;
                    case 11:
                        strUpart = strUpart + "仟";
                        break;
                    case 12:
                        strUpart = strUpart + "亿";
                        break;
                    case 13:
                        strUpart = strUpart + "拾";
                        break;
                    case 14:
                        strUpart = strUpart + "佰";
                        break;
                    case 15:
                        strUpart = strUpart + "仟";
                        break;
                    case 16:
                        strUpart = strUpart + "万";
                        break;
                    default:
                        strUpart = strUpart + "";
                        break;
                }

                strUpper = strUpart + strUpper;
                iTemp = iTemp + 1;
            }

            strUpper = strUpper.Replace("零拾", "零");
            strUpper = strUpper.Replace("零佰", "零");
            strUpper = strUpper.Replace("零仟", "零");
            strUpper = strUpper.Replace("零零零", "零");
            strUpper = strUpper.Replace("零零", "零");
            strUpper = strUpper.Replace("零角零分", "整");
            strUpper = strUpper.Replace("零分", "整");
            strUpper = strUpper.Replace("零角", "零");
            strUpper = strUpper.Replace("零亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("零亿零万", "亿");
            strUpper = strUpper.Replace("零万零圆", "万圆");
            strUpper = strUpper.Replace("零亿", "亿");
            strUpper = strUpper.Replace("零万", "万");
            strUpper = strUpper.Replace("零圆", "圆");
            strUpper = strUpper.Replace("零零", "零");

            // 对壹圆以下的金额的处理
            if (strUpper.Substring(0, 1) == "圆")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "零")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "角")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "分")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "整")
            {
                strUpper = "零圆整";
            }
            functionReturnValue = strUpper;

            if (IsNegative == true)
            {
                return "负" + functionReturnValue;
            }
            else
            {
                return functionReturnValue;
            }
        }

        




        private string[] StrNO = new string[19];
            private string[] Unit = new string[8];
            private string[] StrTens = new string[9];

            #region NumberToString
            public string NumberToString(double Number)
            {
                string Str;
                string BeforePoint;
                string AfterPoint;
                string tmpStr;
                int nBit;
                string CurString;
                int nNumLen;
                Init();
                Str = Convert.ToString(Math.Round(Number, 2));
                if (Str.IndexOf(".") == -1)
                {
                    BeforePoint = Str;
                    AfterPoint = "";
                }
                else
                {
                    BeforePoint = Str.Substring(0, Str.IndexOf("."));
                    AfterPoint = Str.Substring(Str.IndexOf(".") + 1, Str.Length - Str.IndexOf(".") - 1);
                }
                if (BeforePoint.Length > 12)
                {
                    return null;
                }
                Str = "";
                while (BeforePoint.Length > 0)
                {
                    nNumLen = Len(BeforePoint);
                    if (nNumLen % 3 == 0)
                    {
                        CurString = Left(BeforePoint, 3);
                        BeforePoint = Right(BeforePoint, nNumLen - 3);
                    }
                    else
                    {
                        CurString = Left(BeforePoint, (nNumLen % 3));
                        BeforePoint = Right(BeforePoint, nNumLen - (nNumLen % 3));
                    }
                    nBit = Len(BeforePoint) / 3;
                    tmpStr = DecodeHundred(CurString);
                    if ((BeforePoint == Len(BeforePoint).ToString() || nBit == 0) && Len(CurString) == 3)
                    {
                        if (System.Convert.ToInt32(Left(CurString, 1)) != 0 & System.Convert.ToInt32(Right(CurString, 2)) != 0)
                        {
                            tmpStr = Left(tmpStr, tmpStr.IndexOf(Unit[3]) + Len(Unit[3])) + Unit[7] + " " + Right(tmpStr, Len(tmpStr) - (tmpStr.IndexOf(Unit[3]) + Len(Unit[3])));
                        }
                        else
                        {
                            tmpStr = Unit[7] + " " + tmpStr;
                        }
                    }
                    if (nBit == 0)
                    {
                        Str = Convert.ToString(Str + " " + tmpStr).Trim();
                    }
                    else
                    {
                        Str = Convert.ToString(Str + " " + tmpStr + " " + Unit[nBit - 1]).Trim();
                    }
                    if (Left(Str, 3) == Unit[7])
                    {
                        Str = Convert.ToString(Right(Str, Len(Str) - 3)).Trim();
                    }
                    if (BeforePoint == Len(BeforePoint).ToString())
                    {
                        return "";
                    }
                }
                BeforePoint = Str;
                if (Len(AfterPoint) > 0)
                {
                    AfterPoint = Unit[5] + " " + DecodeHundred(AfterPoint) + " " + Unit[6];
                }
                else
                {
                    AfterPoint = Unit[4];
                }
                return BeforePoint + " " + AfterPoint;

            }

            #endregion

            #region Init
            private void Init()
            {
                if (StrNO[0] != "One")
                {
                    StrNO[0] = "One";
                    StrNO[1] = "Two";
                    StrNO[2] = "Three";
                    StrNO[3] = "Four";
                    StrNO[4] = "Five";
                    StrNO[5] = "Six";
                    StrNO[6] = "Seven";
                    StrNO[7] = "Eight";
                    StrNO[8] = "Nine";
                    StrNO[9] = "Ten";
                    StrNO[10] = "Eleven";
                    StrNO[11] = "Twelve";
                    StrNO[12] = "Thirteen";
                    StrNO[13] = "Fourteen";
                    StrNO[14] = "Fifteen";
                    StrNO[15] = "Sixteen";
                    StrNO[16] = "Seventeen";
                    StrNO[17] = "Eighteen";
                    StrNO[18] = "Nineteen";
                    StrTens[0] = "Ten";
                    StrTens[1] = "Twenty";
                    StrTens[2] = "Thirty";
                    StrTens[3] = "Forty";
                    StrTens[4] = "Fifty";
                    StrTens[5] = "Sixty";
                    StrTens[6] = "Seventy";
                    StrTens[7] = "Eighty";
                    StrTens[8] = "Ninety";
                    Unit[0] = "Thousand";
                    Unit[1] = "Million";
                    Unit[2] = "Billion";
                    Unit[3] = "Hundred";
                    Unit[4] = "Only";
                Unit[5] = "And";
                //Unit[5] = "Point";
                Unit[6] = "Cents";
                    //Unit[7] = "And";
                }
            }

            #endregion

            #region DecodeHundred
            private string DecodeHundred(string HundredString)
            {
                int tmp;
                string rtn = "";
                if (Len(HundredString) > 0 && Len(HundredString) <= 3)
                {
                    switch (Len(HundredString))
                    {
                        case 1:
                            tmp = System.Convert.ToInt32(HundredString);
                            if (tmp != 0)
                            {
                                rtn = StrNO[tmp - 1].ToString();
                            }
                            break;
                        case 2:
                            tmp = System.Convert.ToInt32(HundredString);
                            if (tmp != 0)
                            {
                                if ((tmp < 20))
                                {
                                    rtn = StrNO[tmp - 1].ToString();
                                }
                                else
                                {
                                    if (System.Convert.ToInt32(Right(HundredString, 1)) == 0)
                                    {
                                        rtn = StrTens[Convert.ToInt32(tmp / 10) - 1].ToString();
                                    }
                                    else
                                    {
                                        rtn = Convert.ToString(StrTens[Convert.ToInt32(tmp / 10) - 1] + "-" + StrNO[System.Convert.ToInt32(Right(HundredString, 1)) - 1]);
                                    }
                                }
                            }
                            break;
                        case 3:
                            if (System.Convert.ToInt32(Left(HundredString, 1)) != 0)
                            {
                                rtn = Convert.ToString(StrNO[System.Convert.ToInt32(Left(HundredString, 1)) - 1] + " " + Unit[3] + " " + DecodeHundred(Right(HundredString, 2)));
                            }
                            else
                            {
                                rtn = DecodeHundred(Right(HundredString, 2)).ToString();
                            }
                            break;
                        default:
                            break;
                    }
                }
                return rtn;
            }

            #endregion

            #region Left
            private string Left(string str, int n)
            {
                return str.Substring(0, n);
            }
            #endregion

            #region Right
            private string Right(string str, int n)
            {
                return str.Substring(str.Length - n, n);
            }
            #endregion

            #region Len
            private int Len(string str)
            {
                return str.Length;
            }
            #endregion
        }
}
